/**
 * 页面框架
 */
(function ($, owner) {
    owner.frame = function () {
        dux.init();
    };
}(jQuery, window.base = {}));

(function ($, owner) {
    /**
     * 超链接访问
     */
    owner.ajaxLink = function ($el, config) {
        Do('base', function () {
            var defaultConfig = {
                callback: ''
            };
            config = $.extend(defaultConfig, config);
            $($el).click(function () {
                var data = $(this).data();
                var datas = data.data ? data.data : {};
                var field = data.field ? data.field : '';
                var fieldArray = new Array();
                if (data.field) {
                    fieldArray = field.split(',');
                    for (var i = 0; i < fieldArray.length; i++) {
                        datas[fieldArray[i]] = $('#' + fieldArray[i]).val();
                    }
                }
                app.ajax({
                    url: data.url,
                    type: 'post',
                    data: datas,
                    success: function (msg) {
                        app.success(msg);
                        //设置回调
                        if (typeof config.callback === 'function') {
                            config.callback(data.data);
                        }
                        if (typeof config.callback === 'string' && config.callback) {
                            window[config.callback].apply($el, data.data);
                        }
                    },
                    error: function (msg) {
                        app.error(msg);
                    }
                });
            });
        });
    };

    var countdown = 60;
    /**
     * 验证码倒计时
     */
    owner.getCode = function ($el) {
        owner.ajaxLink($el, {
            callback: function () {
                owner._codeTime($el);
            }
        });
    };
    owner._codeTime = function (val) {
        if (countdown == 0) {
            countdown = 60;
            $(val).text('获取验证码').attr('disabled', false);
        } else {
            countdown--;
            $(val).text(countdown + '秒后获取').attr('disabled', true);

            setTimeout(function () {
                owner._codeTime(val)
            }, 1000);
        }
    }

}(jQuery, window.page = {}));

(function ($, owner) {
    /**
     * 商品数量
     */
    owner.num = function ($el) {
        var $layout = $($el), $down = $layout.find('.down'), $up = $layout.find('.up'), $input = $layout.find('input'), maxCount = parseInt($layout.data('count')), callback = $layout.data('callback'), info = $layout.data('info');

        $down.click(function () {
            var curCount = parseInt($input.val());
            var num = curCount - 1;
            if (num <= 1) {
                num = 1;
            }
            upData(num);
        });
        $up.click(function () {
            var curCount = parseInt($input.val());
            var num = curCount + 1;
            if (maxCount && num >= maxCount) {
                num = maxCount;
            }
            upData(num);

        });
        $input.blur(function () {
            var num = parseInt($(this).val());
            if (num <= 1 || num >= maxCount) {
                $input.val(1);
            }
            if (callback != undefined && callback != '') {
                window[callback](num, info, $input);
            }
        });
        function upData(num) {
            if (callback != undefined && callback != '') {
                window[callback](num, info, $input);
            } else {
                $input.val(num);
            }
        }
    };

    /**
     * 统计购物车
     * @param $el
     */
    owner.count = function ($el) {
        var $layout = $($el), $list = $($el).find('[data-list]');
        window.count = function (num, info, $input) {
            app.ajax({
                url: $layout.data('urlNum'),
                data: $.extend({}, info, {qty: num}),
                type: 'post',
                success: function (data) {
                    countCart(data.info);
                    var html = '<span">' + data.row.total + '</span>元';
                    if (data.row.currency.length > 0) {
                        var v = data.row.currency;
                        if(v.type) {
                            html += ' / ';
                        }else {
                            html += ' + ';
                        }
                        html += ' <span class="am-text-danger" >' + v.amount + '</span>' + v.name;
                    }

                    $input.parents('li,tr').find('[data-item-price]').html(html);

                    $input.parents('li,tr').find('[data-item-num]').html(data.row.qty);
                    $input.val(num);
                },
                error: function (msg) {
                    app.error(msg);
                }
            });

        };

        $layout.on('click', '[data-item-del]', function () {
            var $li = $(this).parents('tr,li');
            app.ajax({
                url: $layout.data('urlDel'),
                data: {
                    rowid: $(this).data('itemDel')
                },
                type: 'post',
                success: function () {
                    $li.remove();
                    countCart();
                },
                error: function (msg) {
                    app.error(msg);
                }
            });
        });

        $layout.on('click', '[data-del]', function () {
            var cartCount = $list.find('input[type=checkbox]:checked').length;
            if (cartCount <= 0) {
                app.error('请选择删除商品');
                return;
            }
            var keys = [];
            var ids = [];
            $list.find('input[type=checkbox]:checked').each(function () {
                keys.push($(this).val());
                ids.push('#' + $(this).parents('.dux-pro-item').attr('id'));
            });
            app.ajax({
                url: $layout.data('urlDel'),
                type: 'post',
                data: {
                    rowid: keys.join(',')
                },
                success: function (data, url) {
                    $(ids.join(',')).remove();
                    countCart(data.info);

                },
                error: function (msg) {
                    app.error(msg);
                }
            });
        });

        $layout.on('click', '[data-select-all]', function () {
            if ($(this).prop('checked')) {
                $list.find('input[type=checkbox]').prop("checked", true);
            } else {
                $list.find('input[type=checkbox]').prop("checked", false);
            }
            numCart();
        });

        $list.on('click', 'input[type=checkbox]', function () {
            numCart();
        });

        var numCart = function () {
            var num = $list.find('input[type=checkbox]:checked').length;
            $('[data-select-num]').text(num);
        };

        var countCart = function (info) {
            $('[data-decimal]').text(info.total);
            $('[data-total]').text(info.items);
            var html = '';
            $.each(info.currency, function (k, v) {
                if (v.type) {
                    html += '+ (<span class="am-text-danger">' + v.money + '</span>元/<span class="am-text-danger">' + v.amount + '</span>' + v.name + ')';
                } else {
                    html += '+ <span class="am-text-danger" >' + v.amount + '</span> ' + v.name;
                }
            });
            $('[data-currency]').html(html);

            if (info.items == 0) {
                window.location.reload();
            }
        };
    };
    /**
     * 提交购物车
     * @param $el
     */
    owner.submit = function ($el) {
        var $layout = $($el);

        $layout.on('click', '[data-submit]', function () {
            var remark = [];
            $('[name=remark]').each(function () {
                remark.push($(this).val());
            });
            Do('dialog', function () {
                app.ajax({
                    url: $(this).data('url'),
                    type: 'post',
                    data: {
                        add_id: $('[name=add_id]').val(),
                        cod_status: $('[name=cod_status]').val(),
                        coupon : $('input[name="coupon"]:checked').val(),
                        remark: remark
                    },
                    success: function (msg, url) {
                        layer.open({
                            content: msg,
                            btn: ['确定'],
                            yes: function () {
                                if (url) {
                                    window.location.href = url;
                                } else {
                                    window.location.reload();
                                }
                            }
                        });
                    },
                    error: function (msg) {
                        app.error(msg);
                    }
                });
            });

        });
        $layout.find('[name=delivery]:eq(0)').change();
    };
}(jQuery, window.cart = {}));


